package com.shuzijun.leetcode.editor.cn;

import java.util.Stack;

public class CalculatorLcci{
    public static void main(String[] args) {
         Solution solution = new CalculatorLcci().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int calculate(String s) {
        Stack<Integer> nums = new Stack<>();
        Stack<Character> ops = new Stack<>();
        int i = 0;
        int n = s.length();
        while (i < n){
            char c = s.charAt(i);
            if (c == ' '){
                i++;
            } else if (isDigit(c)) {
                int number= 0;
                while (i < n && isDigit(s.charAt(i))){
                    number = number*10 +(s.charAt(i)-'0');
                    i++;
                }
                nums.push(number);
            }else {
                if (ops.isEmpty() || prior(c,ops.peek())){
                    ops.push(c);
                }else {
                    while (!ops.isEmpty() && !prior(c,ops.peek())){
                        fetchAndCal(nums,ops);
                    }
                    ops.push(c);
                }
                i++;
            }
        }

        while (!ops.isEmpty()){
            fetchAndCal(nums,ops);
        }

        return nums.pop();
    }

        private boolean prior(char a, Character b) {
            if ((a == '*' || a=='/') && (b =='+' || b== '-')){
                return true;
            }
            return false;
        }

        private boolean isDigit(char c) {
            return c >= '0' && c <= '9';
        }

        private void fetchAndCal(Stack<Integer> nums, Stack<Character> ops) {
            Integer number2 = nums.pop();
            Integer number1 = nums.pop();
            Character op = ops.pop();
            int ret = cal(op, number1, number2);
            nums.push(ret);
        }

        private int cal(char op, Integer number1, Integer number2) {
            switch (op){
                case '+': return number1+ number2;
                case '-': return number1- number2;
                case '*': return number1* number2;
                case '/': return number1/ number2;
            }
            return -1;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}